﻿using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using HYHY_Core.Entities.User;
using HYHY_Core.Enums;
using HYHY_Core.Tool.Service;
using HYHY_Core.Tool.Token;
using HYHY_Core.Tool.Tool;
using HYQY_App.Admin_System.Interface;
using HYQY_Core.Entities.User;
using HYQY_Core.Entities.Utils;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static HYQY_App.Admin_System.Dtos.PersonalCenterDto;

namespace HYQY_App.Admin_System.Service
{
    /// <summary>
    /// 个人中心
    /// </summary>
    [ApiDescriptionSettings(ApiGroupEnumsCode.PersonalInfo, Name = "PersonalInfo")]
    public class PersonalCenterService : IDynamicApiController, ITransient, IPersonalCenterService
    {
        /// <summary>
        /// sql
        /// </summary>
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        public PersonalCenterService(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 获取用户信息----弃用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SelectUserInfoOutput> SelectUserInfo(SelectUserInfoInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            // 去掉前后空格
            ToolHelper.TrimStrings(input);

            var puser = await _db.Queryable<PlatformUser>()
               .FirstAsync(it => it.PlatformUserId == input.UserId) ?? throw Oops.Bah("PlatformUser用户信息不存在=>【SelectUserInfo】");
            var acc = await _db.Queryable<Account>()
                .FirstAsync(it => it.UserId == input.UserId) ?? throw Oops.Bah("Account用户信息不存在=>【SelectUserInfo】");

            var output = new SelectUserInfoOutput
            {
                AccountNumber = puser.AccountNumber,
                Email = puser.Email,
                HeadPortraitUrl = puser.HeadPortraitUrl,
                PlatformUserId = puser.PlatformUserId,
                AId = puser.AId,
                WeChat = puser.WeChat,
                LoginCount = acc.LoginCount,
                LastLoginTime = acc.LastLoginTime,
                Message = "成功",
                StatusCode = 200
            };

            return output;
        }

        /// <summary>
        /// 保存头像
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseStatus> SaveTX(SaveTXInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            // 去掉前后空格
            ToolHelper.TrimStrings(input);

            if (string.IsNullOrWhiteSpace(input.PlatformUserId) || string.IsNullOrWhiteSpace(input.HeadPortraitUrl))
            {
                throw Oops.Bah("id或头像url不能为空=>【SaveTX】");
            }

            var puser = await _db.Queryable<PlatformUser>()
                .FirstAsync(it => it.PlatformUserId == input.PlatformUserId) ?? throw Oops.Bah("用户信息不存在=>【SaveTX】");

            puser.HeadPortraitUrl = input.HeadPortraitUrl;

            int count = await _db.Updateable(puser)
                .WhereColumns(it => it.PlatformUserId)
                .UpdateColumns(it => it.HeadPortraitUrl).ExecuteCommandAsync();
            if (count < 1)
            {
                throw Oops.Bah("保存失败=>【SaveTX】");
            }

            return new ResponseStatus { Message = "头像保存成功", StatusCode = 200 };
        }

        /// <summary>
        /// 修改个人基本信息
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseStatus> UpdataUserInfo(UpdataUserInfoInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            // 去掉前后空格
            ToolHelper.TrimStrings(input);

            if (string.IsNullOrWhiteSpace(input.WeChat) || string.IsNullOrWhiteSpace(input.Email))
            {
                throw Oops.Bah("微信号或邮箱不能为空=>【UpdataUserInfo】");
            }

            // 匹配QQ邮箱和网易邮箱的正则表达式
            string emailRegex = @"^(?:\d{5,11}|[a-zA-Z0-9._%+-]{1,64})@(?:qq\.com|163\.com)$";
            if (!Regex.IsMatch(input.Email, emailRegex))
            {
                throw Oops.Bah("目前仅支持QQ、163网易邮箱哦！");
            }

            var puser = await _db.Queryable<PlatformUser>()
                .FirstAsync(it => it.PlatformUserId == input.UserId) ?? throw Oops.Bah("用户信息不存在=>【UpdataUserInfo】");

            puser.WeChat = input.WeChat;
            puser.Email = input.Email;

            int count = await _db.Updateable(puser)
                .WhereColumns(it => it.PlatformUserId)
                .UpdateColumns(it => new
                {
                    it.Email,
                    it.WeChat
                }).ExecuteCommandAsync();
            if (count < 1)
            {
                throw Oops.Bah("保存失败=>【UpdataUserInfo】");
            }

            return new ResponseStatus { Message = "基本信息保存成功", StatusCode = 200 };

        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseStatus> UpdatePassword(UpdatePasswordInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");

            // 去掉前后空格
            ToolHelper.TrimStrings(input);

            if (string.IsNullOrWhiteSpace(input.OldPassword)) { throw Oops.Bah("请输入旧密码"); }

            if (string.IsNullOrWhiteSpace(input.NewPassword)) { throw Oops.Bah("请输入新密码"); }

            if (string.IsNullOrWhiteSpace(input.ConfirmPassword))
            { throw Oops.Bah("请再次输入确认密码"); }

            if (input.OldPassword == input.NewPassword) { throw Oops.Bah("旧密码不能与新密码相同"); }

            if (input.ConfirmPassword != input.NewPassword) { throw Oops.Bah("两次输入的密码不一致"); }

            var acc = await _db.Queryable<Account>()
                .FirstAsync(it => input.AccountNumber == it.AccountNumber)
                ?? throw Oops.Bah("该账号信息不存在");

            if (acc.UnencryptedPad != input.OldPassword) { throw Oops.Bah("旧密码不正确"); }

            // SHA-256加密
            string hashedPassword = PasswordHasher.HashPassword(input.NewPassword);

            acc.UnencryptedPad = input.NewPassword;
            acc.Password = hashedPassword;
            acc.PasswordUPdateMan = user.UserName;
            acc.PasswordUpdateTime = DateTime.Now;

            int count = await _db.Updateable(acc).WhereColumns(it => it.AId)
                .UpdateColumns(it => new
                {
                    it.UnencryptedPad,
                    it.Password,
                    it.PasswordUPdateMan,
                    it.PasswordUpdateTime,
                }).ExecuteCommandAsync();
            if (count < 1) throw Oops.Bah("修改密码失败=>【UpdatePassword】");

            return new ResponseStatus
            { Message = "密码修改成功，即将返回登录页，请重新登录", StatusCode = 200 };
        }
    }
}
